package douyin

import (
	"gitee.com/edodo/flysdk/api"
)

func init() {
	api.RegisterBaseMpApi(api.Douyin, &dyMpApi{})
}

type dyMpApi struct {
}

func GetApiUrl(config *api.MpConfig, path string) string {
	if config.Sandbox {
		return SANDBOX_API_HOST + path
	}
	return API_HOST + path
}

// https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/interface-request-credential/get-access-token
func (wc *dyMpApi) GetAccessToken(config *api.MpConfig) (at *api.AccessToken, e error) {

	// get access token by http request
	p := map[string]any{
		"appid":      config.AppId,
		"secret":     config.AppSecret,
		"grant_type": "client_credential",
	}
	token := new(DyAccessToken)
	if e = api.PostJson(GetApiUrl(config, ACCESS_TOKEN_URL), nil, p, token); e != nil {
		//glog.Errorf("Get access token failed: %v", e)
		return
	}

	at, e = token.ToAccessToken()
	return
}

func (wc *dyMpApi) GetStableAccessToken(config *api.MpConfig, force bool) (at *api.AccessToken, e error) {
	return wc.GetAccessToken(config)
}

// https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/log-in/code-2-session
func (wc *dyMpApi) Code2Session(config *api.MpConfig, at *api.AccessToken, js_code, anonymous_code string) (acs *api.Code2Session, e error) {
	p := map[string]any{
		"appid":          config.AppId,
		"secret":         config.AppSecret,
		"code":           js_code,
		"anonymous_code": anonymous_code,
	}
	sessResp := new(DyCode2Session)
	if e = api.PostJson(GetApiUrl(config, JSCODE_SESSION_URL), nil, p, sessResp); e != nil {
		//glog.Errorf("Get session failed: %v", e)
		return
	}
	acs = sessResp.Data
	return
}

func (wc *dyMpApi) GetPhoneNumber(at *api.AccessToken, code string) (aph *api.PhoneNumber, e error) {
	e = api.ErrUnsupportedApi
	return
}
